var formidable = require('formidable'),
    http = require('http'),
    // util = require('util'),
    fs=require('fs');
http.createServer(function (request, response) {
    if (request.url === '/upload' && request.method.toLowerCase() === 'post') {
        var form = new formidable.IncomingForm();
        form.parse(request, function (err, fields, files) {
            response.writeHead(200, {'Content-Type': 'text/html'});
            // fs.renameSync(files.upload.path,'/tmp/demo.jpg');

            var readStream = fs.createReadStream(files.upload.path)
            var writeStream = fs.createWriteStream("/tmp/test.jpg");

            readStream.pipe(writeStream,function(){
                fs.unlinkSync(files.upload.path);
            })
            // util.pump(readStream, writeStream, function() {
            //     fs.unlinkSync(files.upload.path);
            // });

            response.writeHead(200, {"Content-Type": "text/html"});

            response.write("received image:<br/>");
            response.write("<img src='/show' />");
            response.end();
        });
        return;
    }else if(request.url==='/'||request.url==='/start') {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.end('<form action="/upload" enctype="multipart/form-data" ' +
            'method="post">' +
            '<input type="text" name="title"><br>' +
            '<input type="file" name="upload" multiple="multiple"><br>' +
            '<input type="submit" value="Upload">' +
            '</form>'
        );
    }else if(request.url==='/show'){
        fs.readFile("/tmp/test.jpg", "binary", function (error, file) {
            if (error) {
                response.writeHead(500, {"Content-Type": "text/plain"});
                response.write(error + "\n");
                response.end();
            } else {
                response.writeHead(200, {"Content-Type": "image/png"});
                response.write(file, "binary");
                response.end();
            }
        });
    }
}).listen(8888);